class WebSocketService {
  constructor() {
    this.ws = null
    this.wsUrl = 'wss://api.zctj16888.com/ws1/'
    this.authToken = 'secret123'
    this.isConnected = false
    this.reconnectAttempts = 0
    this.maxReconnectAttempts = 5
    this.reconnectDelay = 3000
    this.pingInterval = null
    this.messageHandlers = new Set()
  }

  connect(csId) {
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      return
    }

    this.ws = new WebSocket(this.wsUrl)

    this.ws.onopen = () => {
      console.log('WebSocket连接已建立')
      this.isConnected = true
      this.reconnectAttempts = 0

      // 发送认证消息
      this.send({
        command: 'cs_join',
        csId: csId,
        authToken: this.authToken
      })

      // 请求历史记录
      this.send({
        command: 'sync_all_sessions',
        csId: csId
      })

      this.startHeartbeat()
    }

    this.ws.onmessage = (e) => {
      try {
        const data = JSON.parse(e.data)
        this.notifyHandlers(data)
      } catch (error) {
        console.error('消息解析错误:', error)
      }
    }

    this.ws.onclose = (e) => {
      console.log('WebSocket连接关闭:', e.code, e.reason)
      this.isConnected = false
      this.stopHeartbeat()

      if (e.code !== 1000 && this.reconnectAttempts < this.maxReconnectAttempts) {
        this.reconnectAttempts++
        setTimeout(() => this.connect(csId), this.reconnectDelay)
      }
    }

    this.ws.onerror = (error) => {
      console.error('WebSocket错误:', error)
      this.isConnected = false
    }
  }

  disconnect() {
    this.stopHeartbeat()
    if (this.ws) {
      this.ws.close()
      this.ws = null
    }
  }

  send(data) {
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      this.ws.send(JSON.stringify(data))
    } else {
      console.error('WebSocket未连接')
    }
  }

  addMessageHandler(handler) {
    this.messageHandlers.add(handler)
  }

  removeMessageHandler(handler) {
    this.messageHandlers.delete(handler)
  }

  notifyHandlers(data) {
    this.messageHandlers.forEach(handler => {
      try {
        handler(data)
      } catch (error) {
        console.error('消息处理错误:', error)
      }
    })
  }

  startHeartbeat() {
    this.stopHeartbeat()
    this.pingInterval = setInterval(() => {
      if (this.ws && this.ws.readyState === WebSocket.OPEN) {
        this.send({ type: 'ping' })
      }
    }, 25000)
  }

  stopHeartbeat() {
    if (this.pingInterval) {
      clearInterval(this.pingInterval)
      this.pingInterval = null
    }
  }
}

// 创建单例实例
const websocketService = new WebSocketService()

export default websocketService
